package com.cartagena.vraptor.extjs;

import java.io.IOException;

import javax.servlet.http.HttpServletResponse;

import br.com.caelum.vraptor.ioc.Component;

import com.google.gson.Gson;
import com.google.gson.JsonObject;

@Component
public class ExtJSGsonImpl implements ExtJSJson {

    private HttpServletResponse response;
    
    private Object object;
    private boolean includeSuccess;
    private boolean successValue;
    
    
    public ExtJSGsonImpl(HttpServletResponse response) {
        this.response = response;
    }


    @Override
    public ExtJSJson from(Object object, ContentType type) {
        response.setContentType(type.getValue());
        response.setCharacterEncoding("UTF-8");
        this.object = object; 
        return this;
    }

    @Override
    public ExtJSJson from(Object object) {
        return from(object, ContentType.JSON);
    }

    @Override
    public ExtJSJson success() {
        return success(true);
    }

    @Override
    public ExtJSJson success(boolean success) {
        includeSuccess = true;
        successValue = success;
        return this;
    }

    @Override
    public ExtJSJson serialize() {
        JsonObject json = new JsonObject();
        json.add("data", new Gson().toJsonTree(object));

        if(includeSuccess) {
            json.addProperty("success", successValue);
        }        
        
        
        try {
            response.getWriter().write(json.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }
        
        return this;
    }

}
